package com.company.pangu.aliyun.mts.client;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.mts.model.v20140618.SubmitJobsRequest;
import com.aliyuncs.mts.model.v20140618.SubmitJobsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.company.nuwa.common.utils.JsonUtils;
import com.company.pangu.aliyun.mts.config.TranscodeConfig;
import com.company.pangu.aliyun.mts.request.TranscodeSubmitJobRequest;
import com.company.pangu.aliyun.mts.response.TranscodeSubmitJobsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * <p>Transcode client</p >
 *
 * @author youyoukele
 * @version 1.0
 * @date 2021/8/31
 */
@Slf4j
public class TranscodeClient {

    private final TranscodeConfig transcodeConfig;

    private final IAcsClient transcodeAcsClient;

    public TranscodeClient(TranscodeConfig transcodeConfig) {
        this.transcodeConfig = transcodeConfig;

        // 创建DefaultAcsClient实例并初始化
        DefaultProfile profile = DefaultProfile.getProfile(
                transcodeConfig.getRegionId(),         // 地域ID
                transcodeConfig.getAccessKeyId(),      // RAM账号的AccessKey ID
                transcodeConfig.getAccessKeySecret()); // RAM账号Access Key Secret
        this.transcodeAcsClient = new DefaultAcsClient(profile);
    }

    /**
     * 提交转码任务
     * <p>
     * SDK链接地址 https://help.aliyun.com/document_detail/67662.html?spm=a2c4g.55729.0.0.ec00387fo7N0IM
     * 接口参数说明 https://help.aliyun.com/document_detail/602834.html?spm=a2c4g.602836.0.0.3bd473c0czY3cR#api-detail-31
     *
     * @param transcodeSubmitJobRequest
     */
    public TranscodeSubmitJobsResponse submitJob(TranscodeSubmitJobRequest transcodeSubmitJobRequest) {
        TranscodeConfig.Ext ext = transcodeConfig.getExt();

        // 创建API请求并设置参数
        SubmitJobsRequest request = new SubmitJobsRequest();
        // Input
        JSONObject input = new JSONObject();
        input.put("Location", ext.getOssInputLocation());
        input.put("Bucket", ext.getOssInputBucket());
        input.put("Object", encodeObject(transcodeSubmitJobRequest.getOssInputObject()));
        request.setInput(input.toJSONString());
        // Output
        JSONObject output = new JSONObject();
        output.put("OutputObject", encodeObject(transcodeSubmitJobRequest.getOssOutputObject()));
        // Ouput->Container
        JSONObject container = new JSONObject();
        container.put("Format", "mp4");
        output.put("Container", container.toJSONString());

        // Ouput->TemplateId
        if (StringUtils.isNotBlank(ext.getTemplateId())) {
            output.put("TemplateId", ext.getTemplateId());
        } else {
            // Ouput->Video
            JSONObject video = new JSONObject();
            video.put("Codec", "H.264");
            video.put("Bitrate", "1000");
            video.put("Fps", "25");
            output.put("Video", video.toJSONString());
        }

        JSONArray outputs = new JSONArray();
        outputs.add(output);
        request.setOutputs(outputs.toJSONString());
        request.setOutputBucket(ext.getOssOutputBucket());
        request.setOutputLocation(ext.getOssOutputLocation());
        // PipelineId
        request.setPipelineId(ext.getPipelineId());
        // 发起请求并处理应答或异常
        SubmitJobsResponse response;
        try {
            response = transcodeAcsClient.getAcsResponse(request);
            log.info("转码结果 {}", JsonUtils.objectToJson(response));
            if (response.getJobResultList().get(0).getSuccess()) {
                log.info("JobId is:" + response.getJobResultList().get(0).getJob().getJobId());
                TranscodeSubmitJobsResponse transcodeSubmitJobsResponse = new TranscodeSubmitJobsResponse();
                BeanUtil.copyProperties(response, transcodeSubmitJobsResponse, true);
                return transcodeSubmitJobsResponse;
            } else {
                throw new RuntimeException("SubmitJobs Failed code:" + response.getJobResultList().get(0).getCode() + " message:" + response.getJobResultList().get(0).getMessage());
            }
        } catch (ServerException e) {
            log.error("转码服务端错误", e);
            throw new RuntimeException("转码服务端错误");
        } catch (ClientException e) {
            log.error("转码客户端错误", e);
            throw new RuntimeException("转码客户端错误");
        }
    }

    private String encodeObject(String ossObject) {
        String result;
        try {
            result = URLEncoder.encode(ossObject, "utf-8").replace("+", "%20");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(ossObject + " URL encode failed");
        }
        return result;
    }


}
